# -*- coding: UTF-8 -*-
# @Project ：VehicleOutlineSizeDetector 
# @File    ：weigh_module.py
# @IDE     ：PyCharm 
# @Date    ：2024/6/5 下午6:47

"""

pip install serial

pip install pyserial要安装这两个库才可以使用
"""
import time
import traceback
import serial
import serial.tools.list_ports
from loguru import logger


def get_serial_port():
    try:
        comports = serial.tools.list_ports.comports()
        serial_port_lst = []
        for port, desc, hwid in comports:
            serial_port_lst.append(port)
        return serial_port_lst
    except Exception as e:
        logger.error(f'获取本机串口异常,信息：{e}, 上下文错误{traceback.format_exc()}')
        return []


class WeighingModule:
    def __init__(self, port, baud_rate, separator, direction):
        self.port = port
        self.baud_rate = baud_rate
        self.separator = separator  # 分隔符
        self.direction = direction  # 方向
        self.ser = serial.Serial(self.port, self.baud_rate)

    def get_weigh(self, stable_count, car_guide_weight=0):
        count = 0
        prev_data = None
        while count < stable_count:
            time.sleep(5)
            if self.ser.in_waiting > 0:
                data = self.ser.readline().decode('utf-8').strip()
                result = self.process_data(data, self.separator, self.direction)
                if result == prev_data:
                    count += 1
                else:
                    count = 1
                    prev_data = result
        return int(prev_data) - int(car_guide_weight)  # 返回称重的数据

    def txt_read_data(self, stable_count, car_guide_weight=0):
        count = 0
        prev_data = None
        with open('../resources/data/Documents.txt', 'r') as read_file:
            for line in read_file.readlines():
                if count == stable_count:
                    break
                result = self.process_data(line.strip(), '=', 'reverse')
                if result == prev_data:
                    count += 1
                else:
                    count = 1
                    prev_data = result
        return int(prev_data) - int(car_guide_weight)

    def timely_get_weigh(self):
        """获取实时数据"""
        with open('../../resources/data/Documents.txt', 'r') as read_file:
            for line in read_file.readlines():
                time.sleep(0.2)
                result = self.process_data(line.strip(), '=', 'reverse')

    def process_data(self, data, separator, direction):
        """处理数据
        :param data: 获取到参数
        :param separator:分隔符，用什么符号进行区分
        :param direction:字符的顺序是正向还是反向"""
        if data[0] != separator:  # 第一个字符不等于给的分隔符，这个数据异常剔除
            return None
        new_data = data[1:]
        if direction == 'reverse':  # 反向的情况
            reverse_data = new_data[::-1]
            result = reverse_data.lstrip('0')  # 删除左边为0的情况
            return result  # 返回一个获取到重量

# obj = WeighingModule('COM1', 115200, '=', 'reverse')
# obj.txt_read_data(125)
#
# print(get_serial_port())
